<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="queryParams.userId" placeholder="用户ID请输入" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="firstName" prop="firstName">
            <el-input v-model="queryParams.firstName" placeholder="firstName请输入" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="lastName" prop="lastName">
            <el-input v-model="queryParams.lastName" placeholder="lastName请输入" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="userName" prop="userName">
            <el-input v-model="queryParams.userName" placeholder="userName请输入" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="isPremium" prop="isPremium">
            <el-input v-model="queryParams.isPremium" placeholder="isPremium请输入" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="游戏mush" prop="mushcoin">
            <el-input v-model="queryParams.mushcoin" placeholder="请输入游戏mush" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="创建日期" style="width: 308px">
            <el-date-picker
              v-model="dateRangeCreateTime"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2024, 1, 1, 0, 0, 0), new Date(2024, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item label="H5推广mush" prop="inviteRewardsTotal">
            <el-input
              v-model="queryParams.inviteRewardsTotal"
              placeholder="请输入H5推广mush"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="存档次数" prop="saveGameCount">
            <el-input v-model="queryParams.saveGameCount" placeholder="请输入存档次数" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="1金币" prop="gold">
            <el-input v-model="queryParams.gold" placeholder="请输入1金币" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="2钻石" prop="diamond">
            <el-input v-model="queryParams.diamond" placeholder="请输入2钻石" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="201硬币" prop="rankCoin">
            <el-input v-model="queryParams.rankCoin" placeholder="请输入201硬币" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="IP地址" prop="ipAddress">
            <el-input v-model="queryParams.ipAddress" placeholder="请输入IP地址" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="IP地址解析" prop="ipAddressName">
            <el-input v-model="queryParams.ipAddressName" placeholder="请输入IP地址解析" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userLoginLog:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userLoginLog:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userLoginLog:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userLoginLog:import']" type="success" plain icon="Top" @click="handleImport()">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userLoginLog:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="userLoginLogList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="ID" align="center" prop="id" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="firstName" align="center" prop="firstName" />
        <el-table-column label="lastName" align="center" prop="lastName" />
        <el-table-column label="userName" align="center" prop="userName" />
        <el-table-column label="isPremium" align="center" prop="isPremium" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="游戏mush" align="center" prop="mushcoin" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable="custom" :sort-orders="['ascending', 'descending']">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="H5推广mush" align="center" prop="inviteRewardsTotal" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="存档次数" align="center" prop="saveGameCount" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="1金币" align="center" prop="gold" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="2钻石" align="center" prop="diamond" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="201硬币" align="center" prop="rankCoin" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="IP地址" align="center" prop="ipAddress" />
        <el-table-column label="IP地址解析" align="center" prop="ipAddressName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="false">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['mushcoin:userLoginLog:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['mushcoin:userLoginLog:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>



  </div>
</template>

<script setup lang="ts">
import { listUserLoginLog, getUserLoginLog, delUserLoginLog, addUserLoginLog, updateUserLoginLog } from '@/api/mushcoin/userLoginLog';
import { UserLoginLogVO, UserLoginLogQuery, UserLoginLogForm } from '@/api/mushcoin/userLoginLog/types';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 表格数据
const userLoginLogList = ref<UserLoginLogVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
// 选中数组
const ids = ref<Array<string | number>>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 总条数
const total = ref(0);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const userLoginLogFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();

/*** 导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 1,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/mushcoin/userLoginLog/importData'
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 默认排序
const defaultSort = ref<any>({ prop: 'createTime', order: 'descending' });
const initFormData: UserLoginLogForm = {};
const data = reactive<PageData<UserLoginLogForm, UserLoginLogQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    userId: undefined,
    firstName: undefined,
    lastName: undefined,
    userName: undefined,
    isPremium: undefined,
    mushcoin: undefined,
    inviteRewardsTotal: undefined,
    saveGameCount: undefined,
    gold: undefined,
    diamond: undefined,
    rankCoin: undefined,
    ipAddress: undefined,
    ipAddressName: undefined,
    orderByColumn: defaultSort.value.prop,
    isAsc: defaultSort.value.order,
    params: {
      createTime: undefined
    }
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询TG游戏登录日志列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  const res = await listUserLoginLog(queryParams.value);
  userLoginLogList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const handleSortChange = (column: any) => {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  userLoginLogFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserLoginLogVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加TG游戏登录日志';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: UserLoginLogVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getUserLoginLog(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改TG游戏登录日志';
};

/** 提交按钮 */
const submitForm = () => {
  userLoginLogFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateUserLoginLog(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addUserLoginLog(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: UserLoginLogVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除TG游戏登录日志编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delUserLoginLog(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'mushcoin/userLoginLog/export',
    {
      ...queryParams.value
    },
    `userLoginLog_${new Date().getTime()}.xlsx`
  );
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = 'TG游戏登录日志导入';
  upload.open = true;
};

/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('mushcoin/userLoginLog/importTemplate', {}, `userLoginLog_template.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

onMounted(() => {
  getList();
});
</script>
